#include "tree.h"
#include "symbol.h"
#include "weed.h"
#include "run1.h"
#include "run2.h"
#include "run3.h"
#include "code.h"
#include "regalloc.h"
#include "print_ll.h"
#include "print_ll_ir.h"
#include "assembler.h"
#include <sys/stat.h>

#include <stdio.h>

int lineno;
int scannerError;
int parseError;
int yyparse();
BODY *thebody;
struct stat s;

int main(){
	lineno = 1;
	parseError = 0;
	scannerError = 0;
	fprintf(stderr,"Scanning and Parsing\n");
	if(yyparse()!=0){
		fprintf(stderr,"***Error 1\n");
		return 1;
	}
	if(parseError+scannerError>0){
		fprintf(stderr,"***Error 1\n");
		return 1;
	}
	fprintf(stderr,"success, 0 errors\n");
	fprintf(stderr,"Weeding\n");
	int weedError = weed_body_root(thebody);
	SymbolTable *rootTable;
	rootTable = initSymbolTable();
	if(weedError==0){
		fprintf(stderr,"success, 0 errors\n");
		fprintf(stderr,"Typechecking\n");
		int run1E = run1(thebody, rootTable);
		int run2E = run2(thebody, rootTable);
		int run3E = 0;
		if(run1E+run2E==0){
			run3E = run3(thebody, rootTable);
		}
		if(run1E+run2E+run3E>0){
			fprintf(stderr,"***Error 1\n");
			return 1;
		}else{
			fprintf(stderr,"success, 0 errors\n");
			ll *front;
			fprintf(stderr,"Code generation\n");
			front = codeBODY(thebody, rootTable);
			/* Now front contains the IR and we make register allocation */
			//print_ll_ir_tree(front);
			fprintf(stderr,"Register allocation\n");
			front = regalloc(front);
			fprintf(stderr,"Assembler generation\n");
			print_ll_tree(front);
			fprintf(stderr,"Program successfully compiled!\n");
		}
	}else{
		fprintf(stderr,"***Error 1\n");
		return 1;
	}
	return 0;
}
